<?php 
namespace app\admin\controller;
class Api extends Common {

	public function runtime(){
		if (\Ebcms::isPost()) {
			\Ebcms::deldir(PROJECT_PATH . 'runtime');
			return $this -> success('清理成功！');
		}
	}

	public function upload(){
		if (isset($_POST['upload_id']) && isset($_POST['file_data'])) {

			$extension_allow = ['jpg','jpeg','png','gif','zip'];

			$path = './uploads/' . date('Y/m/d');
			if (!is_dir($path)) {
				mkdir($path, 0755, true);
			}

			$ext = pathinfo(isset($_POST['name'])?$_POST['name']:'x.xx', PATHINFO_EXTENSION);;

			if (!in_array($ext, $extension_allow)) {
				return $this -> error('该文件类型禁止上传！' . $ext);
			}
			
			$filedata = mb_substr($_POST['file_data'], mb_strpos($_POST['file_data'], 'base64,')+7);
			$filename = $path . '/' . uniqid() . '.' . $ext;
			if (file_put_contents($filename, base64_decode($filedata))) {
				return $this -> success('上传成功！', '', [
					'filename' => substr($filename, 1),
					'upload_id' => \mylib\Input::post('upload_id')
				]);
			}
		}
		return $this -> error('上传失败！');
	}

	public function xhupload(){
		return \mylib\Response::json($this -> _xhupload());
	}

	private function _xhupload(){
		$filename = '';
		$localname = '';
		$extension_allow = ['jpg','jpeg','png','gif','zip'];

		$dir = './uploads/'.date('Y/m/d');
		if (!is_dir($dir)) {
			@mkdir($dir, 0777, true);
		}

		if (isset($_SERVER['HTTP_CONTENT_DISPOSITION']) && preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)) {
			$localname = urldecode($info[2]);
			$ext=pathinfo($localname,PATHINFO_EXTENSION);
			if (!in_array($ext, $extension_allow)) {
				return [
					'err'   =>  '只允许上传'.implode(',', $extension_allow).'格式的文件！',
					'msg'   =>  ''
				];
			}
			$filename = $dir . '/' . md5(uniqid()) . '.' . $ext;
			file_put_contents($filename, file_get_contents('php://input'));
		}elseif (isset($_FILES['filedata'])) {
			$ext=pathinfo($_FILES['filedata']['name'], PATHINFO_EXTENSION);
			$localname = $_FILES['filedata']['name'];
			$filename = $dir . '/' . md5(uniqid()) . '.' . $ext;
			move_uploaded_file($_FILES['filedata']['tmp_name'], $filename);
		}
		if ($filename) {
			return [
				'err'       =>  '',
				'msg'       =>  [
					'url'       =>  '!' . \Ebcms::root() . substr($filename, 1),
					'localfile' =>  $localname,
				]
			];
		}else{
			return [
				'err'   =>  '上传错误！请稍后再试！',
				'msg'   =>  ''
			];
		}
	}
}